package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xwl
 * Date: 2023-08-08
 * Time: 17:28
 */

// 线程不安全
class Counter {
    private int count = 0;

//    public void add() {
//        synchronized (this) {
//            count++;
//        }
//    }
    synchronized public void add() {
            count++;
    }

//    public static void test() {
//        synchronized (Counter.class) {
//
//        }
//    }
    synchronized public static void test() {

    }

    public int get() {
        return this.count;
    }
}

public class ThreadDemo10 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        // 创建俩个线程,每个线程队这个counter自增5w次
        Thread t1 = new Thread( () -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        Thread t2 = new Thread( () -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();

        // 等待俩个线程执行结束,查看结果
        t1.join();
        t2.join();

        // 未加锁时最后结果小于10w
        System.out.println(counter.get());
    }


}
